package com.jytc.framework.filters;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.filter.OncePerRequestFilter;

import com.jytc.framework.constants.SessionNameConstants;
import com.jytc.framework.constants.UrlConstants;

/**
 * @title:后台管理系统登录过滤器
 * @description:判断用户是否已经登录
 * 
 * @author: dongyuese
 * 
 */
public class AdminLoginTokenFilter extends OncePerRequestFilter
{
	protected Logger logger = Logger.getLogger(AdminLoginTokenFilter.class);

	/**
	 * 执行过滤器
	 * 
	 * @param request HttpServletRequest
	 * @param response HttpServletResponse
	 * @param filterChain FilterChain
	 * @throws ServletException,IOException
	 */
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException
	{

		HttpSession session = request.getSession();
		String requestURI = request.getRequestURI();

		if (requestURI.endsWith("/"))
		{
			if (session.getAttribute(SessionNameConstants.ADMIN_LOGIN_TOKEN) == null)
			{
				response.sendRedirect(UrlConstants.LOFIN_PAGE);
				return;
			}
			response.sendRedirect(UrlConstants.MAIN_PAGE);
			return;
		}

		if (this.isFilter(requestURI))
		{
			//			if (session.getAttribute(SessionNameConstants.ADMIN_LOGIN_TOKEN) == null)
			//			{
			//				// 返回信息提示
			//				ResultInfos resultInfo = new ResultInfos();
			//				resultInfo.setIsOverTime(true);
			//				resultInfo.setIsAlert(true);
			//				resultInfo.setAlertInfo("会话已过期，请重新登录！");
			//				request.setAttribute(RequestNameConstants.RESULT_INFO, resultInfo);
			//				request.getRequestDispatcher(UrlConstants.INFORMATION_PAGE).forward(request, response);
			//				return;
			//			}
		}

		filterChain.doFilter(request, response);
	}

	/**
	 * 判断当前请求的URI是否需要过滤
	 * @param uri String 请求的URI
	 * @param notFilterPage String 不需要过滤的页
	 * @return boolean 需要过滤，返回true;否则，返回false
	 */
	private boolean isFilter(String uri)
	{
		boolean result = true;
		if (uri == null)
			return false;

		if (UrlConstants.NOT_FILTER_PAGE_LIST != null && UrlConstants.NOT_FILTER_PAGE_LIST.size() > 0)
		{
			for (int i = 0; i < UrlConstants.NOT_FILTER_PAGE_LIST.size(); i++)
			{
				if (uri.indexOf(UrlConstants.NOT_FILTER_PAGE_LIST.get(i)) >= 0)
				{
					result = false;
					break;
				}
			}
		}
		return result;
	}
}
